package com.y.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.y.config.exception.AccountLoginException;
import com.y.config.exception.BusinessException;
import com.y.entity.Permission;
import com.y.entity.User;
import com.y.entity.UserRole;
import com.y.entity.vo.*;
import com.y.mapper.UserMapper;
import com.y.service.UserRoleService;
import com.y.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.y.utils.Assert;
import com.y.utils.ConstantName;
import com.y.utils.GeneratorHashPassword;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yjh
 * @since 2021-09-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;
    @Resource
    UserRoleService userRoleService;

    @Override
    public User getUserRolesByUsername(String username) {
        return userMapper.getUserRolesByUsername(username);
    }

    @Override
    public List<User> getListUser() {
        return userMapper.getListUser();
    }

    @Override
    public List<Permission> getPermissionByRoleId(Integer id) {
        return null;
    }

    /**
     * 用户登录
     * @param loginUser
     * @return
     */
    @Override
    public User login(User loginUser) {

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", loginUser.getUsername()));
        // 为null 用户名或者密码错误
        Assert.notNull(user,new AccountLoginException(RHttpStatusEnum.USERNAME_OR_PASSWORD_ERROR));
        Assert.isTrue(GeneratorHashPassword.checkHashPassword(loginUser.getPassword(),user.getSalt(),user.getPassword()),new AccountLoginException(RHttpStatusEnum.USERNAME_OR_PASSWORD_ERROR));
        // 账户是否被冻结
        Assert.isTrue(user.getStatus() == 0,new AccountLoginException(RHttpStatusEnum.USER_LOCKED));
        // 登录  查询用户角色
        user = userMapper.getUserRolesByUsername(loginUser.getUsername());
        StpUtil.login(user.getId());

        return user;
    }

    /**
     * 添加用户 注册用户
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R registerUser(RegisterUser user) {

        // 判断两次密码是否相等
        Assert.isEquals(user.getPassword(),user.getCheckPassword(),new BusinessException(RHttpStatusEnum.PASSWORD_NOT_EQUALS));

        // 判断数据库是否有同名用户
        Assert.isNull(userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername())),new BusinessException(RHttpStatusEnum.USERNAME_NOT_AVAILABLE));

        User registerUser = new User();

        //生成随机盐 + 加密密码
        HashPassword hashPassword = GeneratorHashPassword.createHashPassword(user.getPassword());

        // 密码 + salt 添加用户信息
        registerUser.setUsername(user.getUsername())
                .setSalt(hashPassword.getSalt())
                .setPassword(hashPassword.getPassword());

        // 添加用户
        userMapper.insert(registerUser);

        // 条件
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",registerUser.getUsername()).eq("password",registerUser.getPassword());
        // 获取刚添加用户信息
        User one = userMapper.selectOne(userQueryWrapper);
        // 添加为普通用户角色表
        userRoleService.save(new UserRole(one.getId(),ConstantName.GENERAL_USER_ROLE_ID));

        return R.success(RHttpStatusEnum.USER_REGISTER_SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updatePassword(UpdateUserPassword password) {
        // 判断密码是否相等
        Assert.isEquals(password.getPassword(),password.getCheckPassword(),new BusinessException(RHttpStatusEnum.PASSWORD_NOT_EQUALS));

        // 获取正在登录用户ID
        Integer userId =StpUtil.getLoginIdAsInt();

        User user = userMapper.selectById(userId);
        // 判断用户密码是否相同
        if ( GeneratorHashPassword.checkHashPassword(password.getOldPassword(), user.getSalt(),user.getPassword()) ){

            // 生成新密码 + salt
            HashPassword hashPassword = GeneratorHashPassword.createHashPassword(password.getPassword());

            // 存入保存用户密码 salt
            user.setPassword(hashPassword.getPassword())
                    .setSalt(hashPassword.getSalt());

            // 更新用户密码 salt
            userMapper.updateById(user);

            return R.success().setMessage("修改成功，将在下次登录生效");
        }

        return   R.error().setMessage("密码错误，修改失败");


    }

    /**
     * 用户详情和用户所拥有角色
     * @param pageNum
     * @param pageSize
     */
    @Override
    public DataTable<User> getListUser(int pageNum, int pageSize) {
        Page<User> list = PageHelper.startPage(pageNum, pageSize);
        List<User> listUser = userMapper.getListUser();
        return new DataTable<>((int)list.getTotal(),listUser);
    }

    @Override
    public DataTable<User> getListUserByUsername(int pageNum, int pageSize, String username) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> listUser = userMapper.getListUserByUsername(username);
        // 查询总数
        Integer count = userMapper.selectCount(new QueryWrapper<User>().like("username", username));
        return new DataTable<>(count,listUser);
    }


}
